<template>
    <el-dialog v-model="visible" :title="(!dataForm.id ? $t('add') : $t('编辑')) + '品牌'" :close-on-click-modal="false"
        style="width: 30%;top:12%;" :close-on-press-escape="false">
        <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
            label-width="120px">
            <el-form-item label="品牌名称" prop="brandName">
                <el-input v-model="dataForm.brandName" placeholder="请输入品牌名称" style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item label="产地" prop="brandClassId">
                <el-select v-model="dataForm.brandClassId" placeholder="请选择产地" filterable style="width: 300px;"
                    clearable>
                    <el-option v-for="option in brandClassifyOptions" :key="option.id" :label="option.className"
                        :value="option.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="是否首页推荐" prop="tuijianFlag">
                <el-switch v-model="dataForm.tuijianFlag" class="ml-2" style="--el-switch-on-color: #409EFF; --el-switch-off-color: #A8ABAE"  :disabled="isSwitchDisabled"  />
                <el-text>已推荐{{ dataForm.tuijianCount }}/5个品牌</el-text>
            </el-form-item>
          <!-- 新增排序输入框部分 -->
          <el-form-item v-if="dataForm.tuijianFlag" label="首页排序" >
            <el-input v-model="dataForm.tuijianSort" placeholder="请输入" style="width: 300px;"></el-input>
          </el-form-item>
            <el-form-item label="是否首页展示" prop="showFlag">
                <el-switch v-model="dataForm.showFlag" class="ml-2" style="--el-switch-on-color: #409EFF; --el-switch-off-color: #A8ABAE"  :disabled="isSwitchDisabled2"  />
                 <el-text>已展示{{ dataForm.showCount }}/200个品牌</el-text>
            </el-form-item>
            <el-form-item label="品牌图片" prop="imgUrl">
                <el-upload :action="uploadUrl" :file-list="fileList" :before-upload="beforeUploadHandle"
                    :on-success="successHandle" :on-error="uploadErrorHandle" :limit="1" :show-file-list="false"
                    class="brand-upload">
                    <div class="upload-box">
                        <img v-if="!dataForm.imgUrl" src="../../assets/images/upload.png" alt="相机图标" class="icon" />
                        <el-image v-else :src="dataForm.imgUrl" fit="cover"
                            class="uploaded-image" @error="handleImageError" />
                    </div>
                    <template v-slot:tip>
                        <div class="el-upload__tip">
                            {{ t("upload.tip", { format: "jpg、png、gif" }) || '只能上传jpg/png/gif文件' }}
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template v-slot:footer>
            <el-button @click="visible = false" class="quxiao">{{ $t("cancel") }}</el-button>
            <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick, computed } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/cache";
import app from "@/constants/app";
import { IObject } from "@/types/interface";

const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);
const dataFormRef = ref();
const dataForm = reactive({
    id: undefined as number | undefined,
    brandName: "",
    imgUrl: "",
    brandClassId: undefined as number | undefined,
    tuijianFlag: false,
    tuijianSort: undefined as number | undefined,
    showFlag: false,
    tuijianCount: 0,
    showCount: 0
});

// 计算属性：判断是否禁用开关
const isSwitchDisabled = computed(() => {
  // 当已推荐数量达到5个且当前为开启状态时，禁用开关
  return dataForm.tuijianCount >= 5 && !dataForm.tuijianFlag;
});

const isSwitchDisabled2 = computed(() => {
  // 当已推荐数量达到200个且当前为开启状态时，禁用开关
  return dataForm. showCount >= 200 && !dataForm. showFlag;
});


// 上传相关变量
const uploadUrl = ref("");
const fileList = ref<IObject[]>([]);

const rules = ref({
    brandName: [{ required: true, message: t("validate.required"), trigger: "blur" }],
    brandClassId: [{ required: true, message: t("validate.required"), trigger: "change" }],
    imgUrl: [{ required: true, message: t("validate.required"), trigger: "change" }]
});

// 初始化方法
const init = (id?: number | undefined) => {
    visible.value = true;
    dataForm.id = id;
    uploadUrl.value = `${app.api}/sys/oss/upload`;
    fileList.value = [];

    // 重置表单数据
    if (dataFormRef.value) {
        dataFormRef.value.resetFields();
    }

    // 如果是编辑，则获取品牌信息
    if (id) {
        baseService.get(`/base/basebrand/info/${id}`).then((res) => {
            if (res && res.code === 0) {
                const data = res.data;
                dataForm.brandName = data.brandName;
                dataForm.imgUrl = data.imgUrl;
                dataForm.brandClassId = data.brandClassId;
                dataForm.tuijianFlag = data.tuijianFlag > 0;
                dataForm.tuijianSort = data.tuijianSort;
                dataForm.showFlag = data.showFlag > 0;
            }
        });
    }
};

// 上传之前
const beforeUploadHandle = (file: IObject) => {
    if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
        ElMessage.error(t("upload.tip", { format: "jpg、png、gif" }) || '只能上传jpg/png/gif文件');
        return false;
    }

    // 限制图片大小为 2MB
    const maxSize = 2 * 1024 * 1024;
    if (file.size > maxSize) {
        ElMessage.error('上传的图片大小不能超过 2MB，请重新选择！');
        return false;
    }

    return true;
};

// 上传成功
const successHandle = (res: IObject, file: IObject) => {
    if (res.code !== 0) {
        return ElMessage.error(res.msg);
    }

    // 设置图片URL
    dataForm.imgUrl = res.url;
    console.log('图片上传成功:', dataForm.imgUrl);
    // 【新增】清空 fileList，确保下次可重新上传
    fileList.value = [];
    // 手动触发imgUrl字段的验证更新
    nextTick(() => {
        if (dataFormRef.value) {
            dataFormRef.value.validateField('imgUrl');
        }
    });

    ElMessage.success({
        message: t("prompt.success") || '上传成功',
        duration: 500
    });
};

// 上传错误处理
const uploadErrorHandle = (error: any) => {
    console.error('图片上传失败:', error);
    ElMessage.error('图片上传失败，请重试');
};

// 图片加载错误
const handleImageError = () => {
    ElMessage.error('图片加载失败');
};

// 表单提交
const dataFormSubmitHandle = () => {
    if (dataFormRef.value) {
        dataFormRef.value.validate((valid: boolean) => {
            if (!valid) {
                return false;
            }

            const apiUrl = "/base/basebrand";
            const submitData = {
                id: dataForm.id,
                brandName: dataForm.brandName,
                brandClassId: dataForm.brandClassId,
                imgUrl: dataForm.imgUrl,
                tuijianFlag: dataForm.tuijianFlag ? 1 : 0,
                tuijianSort: dataForm.tuijianSort,
                showFlag: dataForm.showFlag ? 1 : 0
            };

            (!dataForm.id ? baseService.post : baseService.put)(`${apiUrl}${!dataForm.id ? '/save' : '/update'}`, submitData).then((res) => {
                if (res && res.code === 0) {
                    ElMessage.success({
                        message: t("prompt.success"),
                        duration: 500,
                        onClose: () => {
                            visible.value = false;
                            emit("refreshDataList");
                        }
                    });
                } else {
                    ElMessage.error(res.msg || '操作失败');
                }
            })
        });
    }
};

// 产地选项
const brandClassifyOptions = ref<any[]>([]);
// 获取产地列表
const getBrandClassifyList = () => {
    baseService.get('/base/basebrandclassify/queryList2').then(res => {
        brandClassifyOptions.value = res.data;
        console.log('产地数据加载成功:', brandClassifyOptions.value);
    }).catch(error => {
        console.error('获取产地数据出错:', error);
        ElMessage.error('获取产地数据出错');
    });
};

const getCount = () => {
  baseService.get('/base/basebrand/getCount').then(res => {
    dataForm.tuijianCount = res.data.tuijianCount;
    dataForm.showCount = res.data.showCount;
    console.log('数据加载成功:', dataForm);
  }).catch(error => {
    console.error('获取数量数据出错:', error);
    ElMessage.error('获取数量数据出错');
  });
};
getBrandClassifyList();
getCount();

defineExpose({
    init
});
</script>

<style scoped lang="scss">
.quxiao {
    border-radius: 5px;
    background: rgba(239, 244, 255, 1);
    color: rgba(22, 119, 255, 1);
    border: 1px solid rgba(22, 119, 255, 1);
}

.uploaded-image {
    width: 100px;
    height: 100px;
    object-fit: cover;
    transition: transform 0.2s;
}

.uploaded-image:hover {
    transform: scale(1.05);
}

.brand-upload {
    .upload-box {
        width: 100px;
        height: 100px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;

        &:hover {
            border-color: #409eff;
        }

        .icon {
            width: 60px;
            height: 60px;
        }
    }

    .el-upload__tip {
        font-size: 12px;
        color: #606266;
        margin-top: 7px;
    }
}
.el-text{
    color: #606266;
    margin-left: 30px;
}
</style>
